/**
 *  编辑页
 *
 * 作者 admin
 * 日期 2024-08-07 16:43:01
 */
layui.use(['jquery', 'febs', 'form', 'validate', 'autocomplete', 'table'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        laydate = layui.laydate,
        form = layui.form,
        table = layui.table,
        autocomplete = layui.autocomplete,
        $view = $('#reportSurveyAssign-edit'),
        $addBtn = $view.find("#addBtn"),
        $accidentType = $('div[name="accidentType"]'),
        tableIns,
        // $surveyUserSelect = $('#surveyUserSelect'),
        validate = layui.validate;
    let tenantId = POPUP_DATA.tenantId;
    let tableDataList = [];
    initDictItemLabel_reportBaseInfo();

    form.verify(validate);
    form.render();
    initFormValue();


    laydate.render({
        elem: "#surveyDeadline",
        done: function (value, date) {
        },
        type: 'date'
    })

    function initDictItemLabel_reportBaseInfo() {
        febs.initDictItemLabel($accidentType, 'SAFETY_ACCIDENT_TYPE', accidentReportData.accidentType);
    }

    $('#inputAutoSurveyUser').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName: 'keywords',
        useType: 'user',
        params: {tenantId: tenantId},
        onSelect: function (suggestion) {
            setSurveyUserAndDeptAttr(suggestion);
            $("#showSurveyUserInfo").show();
        },
    });

    initGroupUserTable()

    function initGroupUserTable(data) {
        tableIns = febs.table.init({
            elem: $view.find('#groupUserTable'),
            id: 'groupUserTable',
            page: false,
            skin: '',
            limit: Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers', width: 60},
                {field: 'surveyTeamId', title: 'id', hide: true},
                {field: 'dutyName', title: '职能名称', minWidth: 220},
                {
                    field: 'teamUserList', title: '小组成员', minWidth: 500, templet: function (d) {
                        var flg = '';
                        var users = d.teamUserList;
                        if (users) {
                            users.forEach((item, index) => {
                                flg += `<span class="layui-badge febs-bg-lightblue" style="margin-left:5px;color: #409eff !important;">${item.realName}<span style="color: red;line-height: 10px;cursor: pointer" data-id=${item.userId} onclick="deleteUser('${d.surveyTeamId}','${item.userId}')"> x </span></span>`
                            })
                        }
                        return flg;
                    }
                },
                {title: '操作', align: 'center', toolbar: '#group-user-option', width: 80},
            ]],
            done: function (res, curr, count) {
            },
            data: tableDataList
        });
    }

    // 删除组员
    window.deleteUser = function (surveyTeamId, userId) {
        tableDataList = tableDataList.map(team => {
            if (team.surveyTeamId === surveyTeamId) {
                if (team.teamUserList.length === 1 && team.teamUserList[0].userId === userId) {
                    return null;
                } else {
                    return {
                        ...team,
                        teamUserList: team.teamUserList.filter(user => user.userId !== userId)
                    };
                }
            }
            return team;
        });
        tableDataList = tableDataList.filter(item => item !== null)
        reloadTab(tableDataList)
    };
    // 添加组员


    table.on('tool(groupUserTable)', function (obj) {
        var layEvent = obj.event;
        var data = obj.data;
        if (layEvent === 'del') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                let i = tableDataList.findIndex(item => item.surveyTeamId === data.surveyTeamId)
                if (i !== -1) {
                    tableDataList.splice(i, 1);
                }
                reloadTab(tableDataList);
                layer.close(index);//关闭弹窗
            });
        }
        if (layEvent === 'add') {
            febs.modal.open('调查部门及负责人选择', 'common/user', {
                btn: ['确认', '关闭'],
                area: $(window).width() <= 750 ? ['95%', '85%'] : ['80%', '85%'],
                data: {
                    tenantId: tenantId,
                    multiple: true,
                },
                yes: function (index, layero) {
                    let selectData = null
                    if (typeof getSelectData === 'function') {
                        selectData = getSelectData()
                    }
                    var arr = tableDataList.filter(item => item.surveyTeamId === data.surveyTeamId);
                    let hasUserFlg = false;
                    if(selectData && arr && arr.length > 0){
                        for (let i = 0; i < selectData.length; i++) {
                            var userArr = arr[0].teamUserList.filter(item => item.userId === selectData[i].userId);
                            if(userArr && userArr.length > 0){
                                febs.alert.warn(selectData[i].uname + '已存在,请勿重复选择!');
                                hasUserFlg = true;
                                return false;
                            }
                        }
                    }
                    if(selectData && !hasUserFlg) {
                        for (let i = 0; i < selectData.length; i++) {
                            let temp = {};
                            temp.userDeptId = selectData[i].deptId;
                            temp.userDeptName = selectData[i].deptName;
                            temp.realName = selectData[i].uname;
                            temp.userId = selectData[i].userId;
                            temp.userNo = selectData[i].userNo;
                            temp.userPostId = selectData[i].postId;
                            temp.userPostName = selectData[i].postName;
                            temp.tenantId = selectData[i].tenantId;
                            temp.surveyTeamId = data.surveyTeamId;
                            arr[0].teamUserList.push(temp)
                        }
                        reloadTab(tableDataList);
                    }
                    layer.close(index);
                },
                btn2: function (index, layero) {
                    layer.close(index);
                    return false;
                }
            });
        }
    });

    $addBtn.on('click', function () {
        febs.modal.open('增加分组', 'common/accidentSurveyTeam', {
            btn: ['确认', '关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%'] : ['1200px', '85%'],
            data: {
                tenantId: tenantId,
                selectList: tableDataList,
                multiple: true,
            },
            yes: function (index, layero) {
                let selectData = null
                if (typeof getSelectData === 'function') {
                    selectData = getSelectData()
                }
                if (null != selectData) {
                    for (var i = 0; i < selectData.length; i++) {
                        var temp = {};
                        temp.surveyTeamId = selectData[i].surveyTeamId;
                        temp.tenantId = $("#tenantId").val();
                        temp.dutyName = selectData[i].dutyName;
                        temp.teamUserList = selectData[i].teamUserList;
                        tableDataList.push(temp);
                    }
                }
                reloadTab(tableDataList);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    function reloadTab(data) {
        tableIns.reload({data: data});
    }


    // $surveyUserSelect.on('click', function () {
    //     febs.modal.open('调查部门及负责人选择', 'common/user', {
    //         btn: ['确认','关闭'],
    //         area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
    //         data:{
    //             tenantId:tenantId,
    //             multiple:false,
    //         },
    //         yes: function (index, layero) {
    //             let selectData = null
    //             if(typeof getSelectData  === 'function'){
    //                 selectData = getSelectData()
    //             }
    //             $("#showSurveyUserInfo").show();
    //             setSurveyUserAndDeptAttr(selectData);
    //             layer.close(index);
    //         },
    //         btn2: function (index, layero) {
    //             layer.close(index);
    //             return false;
    //         }
    //     });
    // });

    function setSurveyUserAndDeptAttr(selectData) {
        $view.find("input[name=surveyDeptId]").val(selectData.deptId);
        $view.find("input[name=surveyDeptName]").val(selectData.deptName);
        $view.find("#surveyDeptNameDiv").text(selectData.deptName);
        $view.find("input[name=surveyUserId]").val(selectData.userId);
        $view.find("input[name=surveyUserName]").val(selectData.userName);
        $view.find("#surveyUserNameDiv").text(selectData.userName);
        $view.find("input[name=surveyRealName]").val(selectData.uname);
        $view.find("input[name=surveyUserNo]").val(selectData.userNo);
        $view.find("#surveyUserNoDiv").text(selectData.userNo);
    }

    function initFormValue() {
        if (accidentReportData) {
            form.val("reportSurveyAssign-edit-form", {
                "reportId": accidentReportData.reportId,
                "tenantId": accidentReportData.tenantId,
                "accidentNo": accidentReportData.accidentNo,
                "accidentType": accidentReportData.accidentType,
                "accidentTitle": accidentReportData.accidentTitle,
                "accidentDate": accidentReportData.accidentDate,
                "status": accidentReportData.status,
                "surveyStatus": accidentReportData.surveyStatus,
                "surveyDeadline": accidentReportData.surveyDeadline,
                "surveyDeptId": accidentReportData.surveyDeptId,
                "surveyDeptName": accidentReportData.surveyDeptName,
                "surveyUserId": accidentReportData.surveyUserId,
                "surveyUserName": accidentReportData.surveyUserName,
                "surveyRealName": accidentReportData.surveyRealName,
                "surveyRemark": accidentReportData.surveyRemark,
                "surveyAuditUserId": accidentReportData.surveyAuditUserId,
                "surveyAuditRealName": accidentReportData.surveyAuditRealName,
                "surveyAuditDate": accidentReportData.surveyAuditDate,
                "surveyAuditRemark": accidentReportData.surveyAuditRemark,

            });
        }
    }

    form.on('submit(reportSurveyAssign-edit-form-submit)', function (data) {
        addOrUpdate(data.field);
        return false;
    });


    function addOrUpdate(data) {
        data.tenantId = tenantId;
        data.teamList = layui.table.cache['groupUserTable'];
        if (data.reportId && data.reportId.length > 0) {
            febs.modal.confirm('提交调查指派信息', '确定提交调查指派信息？', function (index) {
                febs.postArray(ctx + 'accidentReport/surveyAssign', data, function () {
                    layer.closeAll();
                    febs.alert.success('提交成功');
                    $('#febs-accidentReport').find('#query').trigger('click');
                });
            });
        }
    }
});